using MediatR;
using SumerCoreDevOps.Application.Statistics.Queries;
using SumerCoreDevOps.Domain.Entities;
using SumerCoreDevOps.Infrastructure.Data;
using SumerCoreDevOps.Shared.Models;
using TaskStatus = SumerCoreDevOps.Shared.Enums.TaskStatus;

namespace SumerCoreDevOps.Application.Statistics.Handlers;

/// <summary>
/// 获取Dashboard统计数据处理器
/// </summary>
public class GetDashboardStatisticsQueryHandler : IRequestHandler<GetDashboardStatisticsQuery, DashboardStatistics>
{
    private readonly FreeSQLProvider _dbProvider;

    public GetDashboardStatisticsQueryHandler(FreeSQLProvider dbProvider)
    {
        _dbProvider = dbProvider;
    }

    public async Task<DashboardStatistics> Handle(GetDashboardStatisticsQuery request, CancellationToken cancellationToken)
    {
        var today = DateTime.UtcNow.Date;
        var tomorrow = today.AddDays(1);

        // 获取今日构建数据
        var todayInstances = await _dbProvider.Orm.Select<PipelineInstance>()
            .Where(p => p.CreatedAt >= today && p.CreatedAt < tomorrow)
            .ToListAsync(cancellationToken);

        var todayBuilds = todayInstances.Count;
        var todaySuccessBuilds = todayInstances.Count(p => p.Status == TaskStatus.Success);
        var todayFailedBuilds = todayInstances.Count(p => p.Status == TaskStatus.Failed);

        // 计算平均构建时间
        var completedInstances = todayInstances
            .Where(p => p.StartTime.HasValue && p.EndTime.HasValue)
            .ToList();

        var avgBuildTimeMinutes = completedInstances.Any()
            ? completedInstances.Average(p => (p.EndTime!.Value - p.StartTime!.Value).TotalMinutes)
            : 0;

        // 计算成功率
        var successRate = todayBuilds > 0
            ? (double)todaySuccessBuilds / todayBuilds * 100
            : 0;

        // 获取流水线数据
        var totalPipelines = await _dbProvider.Orm.Select<Pipeline>()
            .CountAsync(cancellationToken);

        var activePipelines = await _dbProvider.Orm.Select<Pipeline>()
            .Where(p => p.IsEnabled)
            .CountAsync(cancellationToken);

        return new DashboardStatistics
        {
            TodayBuilds = todayBuilds,
            TodaySuccessBuilds = todaySuccessBuilds,
            TodayFailedBuilds = todayFailedBuilds,
            AvgBuildTimeMinutes = Math.Round(avgBuildTimeMinutes, 1),
            SuccessRate = Math.Round(successRate, 2),
            TotalPipelines = (int)totalPipelines,
            ActivePipelines = (int)activePipelines
        };
    }
}
